<?php
class VmActionModel extends VmArrayModel
{
    protected $resourceId = 'SystemResource';
	protected static $instance;

	public static function GetInstance()
	{
        return self::$instance ? self::$instance : self::$instance = new VmActionModel();
	}

	public function GetCodeByViewId($view_id, $is_mass = false)
	{
        $cond = new SqlCondition();
		$cond->AddString('view_id', $view_id);
		$cond->AddBoolean('is_mass', $is_mass);
		return $this->Find($cond, 'code');
	}

	public function InsertActions()
	{
        $count = 0;
//        $models = VmModelModel::GetInstance()->Find();
		$refs = $this->GetRefModels($models);
		foreach($refs as $modelname => $ref)
		{
			$vm_view = VmViewModel::GetInstance();
			$views = $vm_view->GetByModel($modelname);
			foreach($ref as $fk)
			{
				foreach($views as $view)
				{
					$keyfield = $fk['key_field'];
					$fkfield = $fk['fk_field'];
					$fkview = $vm_view->GetNameByModel($fk['fk_model']);
					$viewname = $view['name'];
					$code = "<a href='[:url_grid:]/$fkview#grid:filter[$fkfield]=[:$keyfield:]'>$fkview</a>";
					if (!$this->actionExist($view['id'], $code))
					{
						$item['view_id'] = $view['id'];
						$item['label'] = $fkview;
						$item['code'] = $code;
						$this->Insert($item);
                        $count++;
					}
				}
			}
		}
        MessageBase::Confirm("Actions inserted: $count");
	}

	public function GetRefModels($models)
	{
		$refs = array();
		foreach($models as $m)
		{
			$model = ModelBase::GetInstanceByName($m['name']);

            $fks = $model->GetForeignKeys();
			if (empty($fks)) continue;

			foreach($fks as $fieldname => $fk)
			{
				$item['key_field'] = $fk->field;
				$item['fk_model'] = $model->GetLowercaseName();
				$item['fk_field'] = $fieldname;
				$refs[$fk->table][] = $item;
			}
		}
		return $refs;
	}

    protected function LoadFields()
    {
        $this->AddField('id', 'int', false, true);
        $this->AddField('view_id');
        $this->AddField('label');
        $this->AddField('code');
        $this->AddField('is_mass', 'bool');

        $this->SetForeignKey('view_id', VmViewModel::GetInstance()->GetTableName(), 'id');
    }
}
?>
